import { appear, disappear } from '../animation';
import { fillStyle } from '../fillStyle';
import { langNameList } from '../config';
import hljs from '../highlight/index';

// item
let langSelect, langTitle, langList;

// flag
let langListAppearFlag = false;

// listener 
function addLangSelectListener(node) {
  // default 'C'
  if(!node.dataset.lang) node.dataset.lang = 'C';
  for(let i = 0; i < node.children.length; i++) {
    let child = node.children.item(i);
    child.innerHTML = hljs.highlight(child.innerText, {
      language: node.dataset.lang
    }).value;
  }

  node.addEventListener('click', e => {
    e.stopPropagation();

    let rect = node.getBoundingClientRect();

    fillStyle(langSelect, {
      display: 'block',
      top: `${rect.top + 10}px`,
      left: `${rect.left + rect.width - 140}px`
    });
    langTitle.innerText = node.dataset.lang;

    langSelect.$el = node;
  })
}

function traceCode(node) {
  let codeParts = node.querySelectorAll('code');
  codeParts.forEach(code => {
    addLangSelectListener(code);
  })
}

function initLangSelect(node, codeBlockCallback) {
  if(!(node instanceof Node) || node.nodeType !== Node.ELEMENT_NODE) {
    return;
  }

  // clear node
  node.innerHTML = '';

  // DOM
  langSelect = node;
  langSelect.id = 'langSelect';
  langTitle = document.createElement('P');
  langTitle.id = 'langTitle';
  langList = document.createElement('UL');
  langList.id = 'langList';

  langSelect.appendChild(langTitle);
  langSelect.appendChild(langList);

  // animation
  disappear(langList);

  langSelect.addEventListener('click', e => {
    if(langListAppearFlag) {
      disappear(langList);
    } else {
      appear(langList);
    }
    langListAppearFlag = !langListAppearFlag;
    e.stopPropagation();
  });

  document.addEventListener('click', e => {
    disappear(langSelect);
  });

  // add list item
  langNameList.forEach(name => {
    let li = document.createElement('li');
    li.classList.add('lang-item');
    li.innerText = name.toUpperCase();
    langList.appendChild(li);

    li.addEventListener('click', event => {
      event.stopPropagation();
      langListAppearFlag = false;
      disappear(langList);
      langTitle.innerText = event.target.innerText;

      let codeBlock = langSelect.$el;

      if(!(codeBlock instanceof Node
        && codeBlock.nodeType === Node.ELEMENT_NODE)) return;

      if(typeof codeBlockCallback === 'function')
        codeBlockCallback(event.target.innerText, codeBlock);
    })
  })
}

export {
  initLangSelect,
  addLangSelectListener,
  traceCode
}